package com.maybach.web.controller.product;

import com.alibaba.fastjson.JSON;
import com.maybach.common.enums.PartnerStatusEnum;
import com.maybach.common.model.ImportModuleDO;
import com.maybach.common.model.PartnerDO;
import com.maybach.common.model.UserDO;
import com.maybach.common.query.ImportModuleQuery;
import com.maybach.common.query.PartnerQuery;
import com.maybach.common.query.UserQuery;
import com.maybach.core.ao.ImportModuleAO;
import com.maybach.core.form.product.ModuleForm;
import com.maybach.core.form.product.ModuleQueryForm;
import com.maybach.core.manager.ImportModuleManager;
import com.maybach.core.manager.PartnerManager;
import com.maybach.core.manager.UserManager;
import com.maybach.util.MaybachUtil;
import com.maybach.util.query.support.PageResult;
import com.maybach.web.framework.util.WebUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.List;

/**
 * Created by pyshift on 16/3/16.
 */
@Controller
@RequestMapping("/product")
public class ModuleController {

	@Autowired
	private UserManager userManager;
	@Autowired
	private ImportModuleManager importModuleManager;
	@Autowired
	private PartnerManager partnerManager;
	@Autowired
	private ImportModuleAO importModuleAO;

	@RequestMapping(value = "/module")
	public ModelAndView module(@RequestParam(required = false, value = "mobile") String mobile, ModelMap model) {
		ModelAndView mav = new ModelAndView();
		if (StringUtils.isNotBlank(mobile)) {
			UserQuery userQuery = new UserQuery();
			userQuery.createCriteria().andLoginNameEqualTo(mobile);
			userQuery.createCriteria().andPartnerIdIsNotNull();
			List<UserDO> userList = userManager.selectByQuery(userQuery);
			if (CollectionUtils.isNotEmpty(userList) && userList.size() == 1 && userList.get(0) != null) {
				Long partnerId = userList.get(0).getPartnerId();
				return new ModelAndView("redirect:/product/addModule.htm?partnerId=" + partnerId);
			} else {
				PartnerQuery partnerQuery = new PartnerQuery();
				partnerQuery.createCriteria().andContactsPhoneEqualTo(mobile);
				partnerQuery.createCriteria().andStatusEqualTo(PartnerStatusEnum.normal.getCode());
				List<PartnerDO> partnerDOs = partnerManager.selectByQuery(partnerQuery);
				if (CollectionUtils.isNotEmpty(partnerDOs) && partnerDOs.size() == 1 && partnerDOs.get(0) != null) {
					Long partnerId = partnerDOs.get(0).getId();
					return new ModelAndView("redirect:/product/addModule.htm?partnerId=" + partnerId);
				}
			}
			model.addAttribute("msg", "找不到经销商" + mobile);
			model.addAttribute("mobile", mobile);
		}
		mav.setViewName("/product/module");
		return mav;
	}

	@RequestMapping(value = "/addModule.htm")
	public String addModule(@RequestParam Long partnerId, ModelMap model) {
		PartnerDO partnerDO = partnerManager.selectByPrimaryKey(partnerId);
		if (partnerDO == null) {
			return "/product/module";
		}
		if (model.containsAttribute("moduleForm")) {
			return "/product/addModule";
		}
		ImportModuleQuery importModuleQuery = new ImportModuleQuery();
		importModuleQuery.createCriteria().andPartnerIdEqualTo(partnerId).andStatusEqualTo(1);
		List<ImportModuleDO> importModuleDOs = importModuleManager.selectByQuery(importModuleQuery);
		if (CollectionUtils.isNotEmpty(importModuleDOs) && importModuleDOs.size() == 1
				&& importModuleDOs.get(0) != null) {
			ImportModuleDO importModuleDO = importModuleDOs.get(0);
			ModuleForm moduleForm = JSON.parseObject(importModuleDO.getModule(), ModuleForm.class);
			setNumToLetter(moduleForm);
			moduleForm.setId(importModuleDO.getId());
			model.addAttribute("moduleForm", moduleForm);
		} else {
			ModuleForm moduleForm = new ModuleForm();
			moduleForm.setCompanyName(partnerDO.getCorpName());
			moduleForm.setMobile(partnerDO.getContactsPhone());
			moduleForm.setPartnerId(partnerDO.getId());
			model.addAttribute("moduleForm", moduleForm);
		}
		return "/product/addModule";
	}

	/**
	 * 列表页面
	 *
	 * @param model
	 * @return
	 */
	@RequiresAuthentication
	@RequestMapping(value = "/moduleList.htm")
	public String list(@Valid ModuleQueryForm moduleQueryForm, ModelMap model) {
		if (null == moduleQueryForm) {
			moduleQueryForm = new ModuleQueryForm();
		}
		if (!model.containsAttribute("moduleQueryForm")) {
			model.addAttribute(moduleQueryForm);
		}

		PageResult<ImportModuleDO> importModuleDOPageResult = importModuleAO.queryImportModule(moduleQueryForm);
		model.addAttribute("pageResult", importModuleDOPageResult);
		return "/product/moduleList";
	}

	@RequiresAuthentication
	@RequestMapping(value = "/doInsert", method = RequestMethod.POST)
	public String doImport(@Valid ModuleForm moduleForm, BindingResult bindingResult,
			RedirectAttributes redirectAttributes, ModelMap model, HttpServletRequest request) {
		if (bindingResult.hasErrors()) {
			WebUtil.storeFlashAttribute(redirectAttributes, model);
			return "redirect:" + WebUtil.getLastUrlFromReferer(request);
		}

		ImportModuleDO record = new ImportModuleDO();
		record.setMobile(moduleForm.getMobile());
		record.setPartnerId(moduleForm.getPartnerId());
		record.setCompanyName(moduleForm.getCompanyName());
		record.setFeature(moduleForm.getFeature());

		// 转换成数字
		setLetterToNum(moduleForm);

		record.setModule(JSON.toJSONString(moduleForm));
		if (moduleForm.getId() != null) {
			record.setId(moduleForm.getId());
			importModuleManager.updateByPrimaryKeySelective(record);
		} else {
			record.setStatus(1);
			importModuleManager.insertSelective(record);
		}
		return "redirect:/product/moduleList.htm";
	}

	private void setNumToLetter(ModuleForm moduleForm) {
		moduleForm.setStandard(setNumToLetter(moduleForm.getStandard()));
		moduleForm.setType(setNumToLetter(moduleForm.getType()));
		moduleForm.setModel(setNumToLetter(moduleForm.getModel()));
		moduleForm.setFacade(setNumToLetter(moduleForm.getFacade()));
		moduleForm.setTrim(setNumToLetter(moduleForm.getTrim()));
		moduleForm.setPrice(setNumToLetter(moduleForm.getPrice()));
		moduleForm.setConfigure(setNumToLetter(moduleForm.getConfigure()));
		moduleForm.setRemark(setNumToLetter(moduleForm.getRemark()));
		moduleForm.setQuantity(setNumToLetter(moduleForm.getQuantity()));
		moduleForm.setFrameNo(setNumToLetter(moduleForm.getFrameNo()));
		moduleForm.setFuel(setNumToLetter(moduleForm.getFuel()));
	}

	private String setNumToLetter(String strValue) {
		StringBuilder sb = new StringBuilder();
		List<Integer> integer = MaybachUtil.getInteger(strValue);
		for (Integer i : integer) {
			char c = (char) (i + 64);
			sb.append(c).append(",");
		}
		if (StringUtils.isNotBlank(sb.toString())) {
			return sb.deleteCharAt(sb.length() - 1).toString();
		} else {
			return "";
		}
	}

	private void setLetterToNum(ModuleForm moduleForm) {
		moduleForm.setStandard(setLetterToNum(moduleForm.getStandard()));
		moduleForm.setType(setLetterToNum(moduleForm.getType()));
		moduleForm.setModel(setLetterToNum(moduleForm.getModel()));
		moduleForm.setFacade(setLetterToNum(moduleForm.getFacade()));
		moduleForm.setTrim(setLetterToNum(moduleForm.getTrim()));
		moduleForm.setPrice(setLetterToNum(moduleForm.getPrice()));
		moduleForm.setConfigure(setLetterToNum(moduleForm.getConfigure()));
		moduleForm.setRemark(setLetterToNum(moduleForm.getRemark()));
		moduleForm.setQuantity(setLetterToNum(moduleForm.getQuantity()));
		moduleForm.setFrameNo(setLetterToNum(moduleForm.getFrameNo()));
		moduleForm.setFuel(setLetterToNum(moduleForm.getFuel()));
	}

	private String setLetterToNum(String strValue) {
		StringBuilder sb = new StringBuilder();
		for (int index = 0; index < strValue.length(); index++) {
			char charAt = strValue.charAt(index);
			if (charAt >= 65 && charAt <= 90) {
				sb.append((int) charAt - 64);
			} else if (charAt >= 97 && charAt <= 122) {
				sb.append((int) charAt - 96);
			} else {
				sb.append(charAt);
			}
		}
		return sb.toString();
	}
}
